package com.dearbinge.data.service.impl.ShowField;

import com.baomidou.mybatisplus.plugins.Page;
import com.dearbinge.data.api.ShowField.ShowFieldService;
import com.dearbinge.data.dao.*;
import com.dearbinge.data.pojo.commodity.CommodityMessage;
import com.dearbinge.data.pojo.orderDetailTable.OrderDetailTable;
import com.dearbinge.data.pojo.position.Position;
import com.dearbinge.data.pojo.showField.ShowField;
import com.dearbinge.data.pojo.thumbs.Thumbs;
import com.dearbinge.data.pojo.transactionFlow.TransactionFlow;
import com.dearbinge.data.pojo.user.User;
import com.dearbinge.data.pojo.userWallet.UserWallet;
import com.dearbinge.utils.Base64Util;
import com.dearbinge.utils.LocationUtils;
import com.dearbinge.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service(value = "showFieldService")
public class ShowFieldServiceImpl implements ShowFieldService {

    @Autowired
    private ShowFieldMapper showFieldMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ThumbsMapper thumbsMapper;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private OrderDetailTableMapper orderDetailTableMapper;

    @Autowired
    private TransactionFlowMapper transactionFlowMapper;

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Autowired
    private CommodityMessageMapper commodityMessageMapper;

    @Override
    public Integer update(ShowField showField) {
        Integer dataCode = showFieldMapper.update(showField);
        return dataCode;
    }

    @Override
    public Integer insert(ShowField showField) {
        Integer dataCode = showFieldMapper.insert(showField);
        Integer resCode = 0;
        if (!StringUtils.isEmpty(showField.getLongitude()) && !StringUtils.isEmpty(showField.getLatitude())){
            Position position = positionMapper.getByUserId(showField.getUserId());
            if (position != null){
                position.setLatitude(showField.getLatitude());
                position.setLongitude(showField.getLongitude());
                position.setPositionName(showField.getPositionName());
                position.setPositionDetailedName(showField.getPositionDetailedName());
                resCode = positionMapper.update(position);
                if(resCode > 0)updateByUserId(showField, position);
            }else {
                position = new Position();
                position.setLatitude(showField.getLatitude());
                position.setLongitude(showField.getLongitude());
                position.setPositionName(showField.getPositionName());
                position.setPositionDetailedName(showField.getPositionDetailedName());
                position.setUserId(showField.getUserId());
                resCode = positionMapper.insert(position);
                if(resCode > 0)updateByUserId(showField, position);
            }
        }
        if (dataCode > 0 && showField.getOrderId() != null){
            OrderDetailTable orderDetailTable = orderDetailTableMapper.getById(showField.getOrderId());
            if (orderDetailTable != null){
                TransactionFlow transactionFlow = new TransactionFlow();
                transactionFlow.setUserId(showField.getUserId());
                transactionFlow.setTfType(1);
                transactionFlow.setMoney(orderDetailTable.getShowMoney());
                transactionFlow.setSource(4);
                transactionFlow.setFtStatus(1);
                Integer code = transactionFlowMapper.insert(transactionFlow);
                if (code > 0){
                    UserWallet byUserId = userWalletMapper.getByUserId(showField.getUserId());
                    if (byUserId != null) {
                        Integer status = userWalletMapper.updateMoneyByUserId(showField.getUserId(), orderDetailTable.getShowMoney());
                        if (status < 1) {
                            dataCode = status;
                        }
                    }else {
                        BigDecimal bigDecimal = new BigDecimal("0");
                        UserWallet userWallet = new UserWallet();
                        userWallet.setUserId(showField.getUserId());
                        userWallet.setFrozenMoney(orderDetailTable.getShowMoney());
                        userWallet.setWalletMoney(orderDetailTable.getShowMoney());
                        userWallet.setUnfrozenMoney(bigDecimal);
                        dataCode = userWalletMapper.insert(userWallet);
                    }
                }
            }
        }
        return dataCode;
    }

    private void updateByUserId(ShowField showField, Position position) {
            ShowField sh = new ShowField();
            sh.setPositionId(position.getId().toString());
            sh.setUserId(showField.getUserId());
            sh.setId(showField.getId());
            showFieldMapper.updateByUserId(sh);
    }

    @Override
    public Integer delete(Integer id) {
        Integer dataCode = showFieldMapper.delete(id);
        return dataCode;
    }

    @Override
    public Map<String,Object> getById(Integer id) {
        Map<String,Object> map = new HashMap<String, Object>();
        ShowField showField = showFieldMapper.getById(id);
        User users = new User();
        if (showField != null){
            users = getUserById(showField);
        }
        map.put("showField",showField == null ? null : showField);
        map.put("user",users == null ? null : users);
        return map;
    }

    public PageResult<List<Map<String, Object>>> getByPage(Double minLat, Double minLng, Double maxLat, Double maxLng, String userId, String commodityId, Integer thumbsType, Double longitude, Double latitude, Integer pageNo, Integer pageSize, String positionName, String positionDetailedName, Integer id) {
        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude) && !StringUtils.isEmpty(userId)){
            Position position = positionMapper.getByUserId(userId);
            if (position != null){
                position.setLatitude(latitude.toString());
                position.setLongitude(longitude.toString());
                position.setPositionName(positionName);
                position.setPositionDetailedName(positionDetailedName);
                positionMapper.update(position);
            }else {
                position = new Position();
                position.setLatitude(latitude.toString());
                position.setLongitude(longitude.toString());
                position.setPositionName(positionName);
                position.setPositionDetailedName(positionDetailedName);
                position.setUserId(userId);
                Integer dataCode = positionMapper.insert(position);
                if (dataCode > 0){
                    ShowField showField = new ShowField();
                    showField.setPositionId(position.getId().toString());
                    showField.setUserId(userId);
                    showFieldMapper.updateByUserId(showField);
                }
            }
        }
        Integer count = showFieldMapper.count(userId,commodityId,thumbsType,minLat,minLng,maxLat,maxLng,longitude,latitude,id);
        pageNo = (null == pageNo || pageNo < 1) ? 1 : pageNo;
        pageSize = (null == pageSize || pageSize < 0) ? 1 :pageSize;
        Page page = new Page(pageNo,pageSize);
        List<Map<String,Object>> mapperList = showFieldMapper.getByPage(userId,commodityId,thumbsType,minLat,minLng,maxLat,maxLng,longitude,latitude,id,page);
        if (mapperList != null && mapperList.size() > 0) {
            for (Map<String,Object> mapL : mapperList){
                mapL.put("dist",null);
                if (mapL.get("uName") != null) {
                    mapL.put("uName", Base64Util.decodeData(mapL.get("uName").toString()));
                }
                if (!StringUtils.isEmpty(mapL.get("longitude")) && !StringUtils.isEmpty(latitude)){
                    Double lon = Double.parseDouble(mapL.get("longitude").toString());
                    Double lat = Double.parseDouble(mapL.get("latitude").toString());
                    String distance = LocationUtils.getDistance(latitude, longitude, lat, lon);
                    mapL.put("dist",distance);
                }
                String thumbsType1 = mapL.get("thumbsType") == null ? null : mapL.get("thumbsType").toString();
                if (thumbsType1 != null && thumbsType1.equals("1") || thumbsType1.equals("2")){
                    CommodityMessage commodityMessage = commodityMessageMapper.getById(Integer.parseInt(mapL.get("commodityId").toString()));
                    mapL.put("commodityMessage",null == commodityMessage ? null : commodityMessage);
                }else {
                    mapL.put("commodityMessage",null);
                }
            }
        }
        Integer max = count % pageSize == 0 ? count / pageSize : count / pageSize +1;
        PageResult<List<Map<String,Object>>> pageResult = new PageResult<List<Map<String,Object>>>(mapperList);
        pageResult.setMaxPageSize(max);
        return pageResult;
    }

    private Thumbs getThumbs(String isThumbsId, Integer thumbsType, String userId){
        Thumbs thumbs = thumbsMapper.getIsThumbs(isThumbsId, thumbsType, userId);
        return thumbs;
    }


    private User getUserById(ShowField showField){
        User user = userMapper.getById(Integer.valueOf(showField.getUserId()));
        return user;
    }
}
